﻿namespace FFF.Test
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    using Abp.Application.Services;
    using Abp.Extensions;
    using Hangfire;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.StaticFiles;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Options;
    using Microsoft.IdentityModel.Logging;
    using Microsoft.IdentityModel.Tokens;
    using Senparc.CO2NET;
    using Senparc.CO2NET.RegisterServices;
    using Senparc.Weixin;
    using Senparc.Weixin.Entities;
    using Senparc.Weixin.MP;
    using Senparc.Weixin.RegisterServices;
    using Senparc.Weixin.TenPay;
    using Senparc.Weixin.WxOpen;
    using Swashbuckle.AspNetCore.Swagger;
    using Swashbuckle.AspNetCore.SwaggerGen;
    using FFF.Test.Util.Consts;
    using FFF.Test.Util.Web;

    /// <summary>
    /// mvc处理配置配置
    /// </summary>
    public static class MVCConfigurer
    {
        /// <summary>
        /// 配置service
        /// </summary>
        /// <param name="services">程序的服务对象</param>
        /// <param name="configuration">程序的配置对象</param>
        /// <param name="env">环境节点</param>
        public static void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostingEnvironment env)
        {
            Directory.SetCurrentDirectory(env.ContentRootPath);
            Server.ContentRootPath = env.ContentRootPath;

            services.AddResponseCompression(); // 启用压缩

            ViewsConfigurer.ConfigureServices(services, configuration, env); // 配置查询views目录

            services.AddMvc(c =>
            {
                c.Filters.Add(typeof(YdmMyAuthorityFilterAttribute));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddRazorOptions(op => op.AllowRecompilingViewsOnFileChange = true);

            services.AddSession(o =>
            {
                o.IdleTimeout = TimeSpan.FromHours(1);
            });

            if (env.IsProduction())
            {
                // 跨域配置
                services.AddCors(option => option.AddPolicy(
                    "mycors",
                    policy => policy
                    .WithOrigins(AppConfigConsts.CorsOrigins.Split(","))
                    .WithMethods("GET", "POST")
                    ));
            }
            else
            {
                // 跨域配置
                services.AddCors(option => option.AddPolicy(
                    "mycors",
                    policy => policy
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .AllowAnyOrigin()));
            }
        }

        /// <summary>
        /// 配置中间件
        /// </summary>
        /// <param name="app">app环境</param>
        /// <param name="env">env的环境</param>
        public static void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.Use(async (context, next) =>
            {
                if (AppConfigConsts.AppDomain.IsNullOrEmpty())
                {
                    AppConfigConsts.AppDomain = context.Request.Scheme + "://" + context.Request.Host.Value;
                }

                await next();
            });

            app.UseSession();
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                IdentityModelEventSource.ShowPII = true;
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            // 添加跨域配置
            app.UseCors("mycors");

            app.UseStaticFiles();

            //app.UseStaticFiles(new StaticFileOptions()
            //{
            //    FileProvider = new PhysicalFileProvider(
            //    Path.Combine(System.AppContext.BaseDirectory, @"Views")),
            //    RequestPath = new PathString("/Views"),
            //    ContentTypeProvider = new FileExtensionContentTypeProvider(
            //    new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            //    {
            //        { ".js", "application/javascript" },
            //        { ".css", "text/css" },
            //    })
            //});

            app.UseStaticFiles(new StaticFileOptions()
            {
                ContentTypeProvider = new FileExtensionContentTypeProvider()
                {
                    Mappings =
                    {
                        [".exe"] = "application/octect-stream",
                        [".amr"] = "audio/mpeg"
                    }
                }
            });

            app.UseResponseCompression(); // 启用压缩
        }
    }
}
